// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/expr.h>
#include <pollux/expression/vector_function.h>
#include <pollux/functions/lib/lambda_function_util.h>
#include <pollux/functions/lib/rows_translation_util.h>
#include <pollux/vector/function_vector.h>

namespace kumo::pollux::functions {
    namespace {
        // See documentation at https://prestodb.io/docs/current/functions/map.html
        class TransformValuesFunction : public exec::VectorFunction {
        public:
            void apply(
                const SelectivityVector &rows,
                std::vector<VectorPtr> &args,
                const TypePtr &outputType,
                exec::EvalCtx &context,
                VectorPtr &result) const override {
                POLLUX_CHECK_EQ(args.size(), 2);

                // Flatten input map.
                exec::LocalDecodedVector mapDecoder(context, *args[0], rows);
                auto &decodedMap = *mapDecoder.get();

                auto flatMap = flattenMap(rows, args[0], decodedMap);

                std::vector<VectorPtr> lambdaArgs = {
                    flatMap->mapKeys(), flatMap->mapValues()
                };
                auto numValues = flatMap->mapValues()->size();

                SelectivityVector validRowsInReusedResult =
                        toElementRows<MapVector>(numValues, rows, flatMap.get());

                VectorPtr transformedValues;

                auto elementToTopLevelRows = getElementToTopLevelRows(
                    numValues, rows, flatMap.get(), context.pool());

                // Loop over lambda functions and apply these to values of the map.
                // In most cases there will be only one function and the loop will run once.
                auto it = args[1]->as_unchecked<FunctionVector>()->iterator(&rows);
                while (auto entry = it.next()) {
                    auto valueRows =
                            toElementRows<MapVector>(numValues, *entry.rows, flatMap.get());
                    auto wrapCapture = toWrapCapture<MapVector>(
                        numValues, entry.callable, *entry.rows, flatMap);

                    entry.callable->apply(
                        valueRows,
                        &validRowsInReusedResult,
                        wrapCapture,
                        &context,
                        lambdaArgs,
                        elementToTopLevelRows,
                        &transformedValues);
                }

                // Set nulls for rows not present in 'rows'.
                BufferPtr newNulls = addNullsForUnselectedRows(flatMap, rows);

                auto localResult = std::make_shared<MapVector>(
                    flatMap->pool(),
                    outputType,
                    std::move(newNulls),
                    rows.end(),
                    flatMap->offsets(),
                    flatMap->sizes(),
                    flatMap->mapKeys(),
                    transformedValues);
                context.moveOrCopyResult(localResult, rows, result);
            }

            static std::vector<std::shared_ptr<exec::FunctionSignature> > signatures() {
                // map(K, V1), function(K, V1) -> V2 -> map(K, V2)
                return {
                    exec::FunctionSignatureBuilder()
                    .typeVariable("K")
                    .typeVariable("V1")
                    .typeVariable("V2")
                    .returnType("map(K,V2)")
                    .argumentType("map(K,V1)")
                    .argumentType("function(K,V1,V2)")
                    .build()
                };
            }
        };
    } // namespace

    /// transform_values is null preserving for the map. But
    /// since an expr tree with a lambda depends on all named fields, including
    /// captures, a null in a capture does not automatically make a
    /// null result.

    POLLUX_DECLARE_VECTOR_FUNCTION_WITH_METADATA(
        udf_transform_values,
        TransformValuesFunction::signatures(),
        exec::VectorFunctionMetadataBuilder().defaultNullBehavior(false).build(),
        std::make_unique<TransformValuesFunction>());
} // namespace kumo::pollux::functions
